package com.gtworldmobile.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.mixare.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gtworld.android.slideout.SlideoutActivity;
import com.gtworldmobile.classes.Uploader;

public class SendImageActivity extends Activity {
	
	private  String URL = "";
	private String CREARPOI_SERVICES="GTWorld/CrearPoi";

		public String ip_cargada= "";
	
	String nombrePref = "preferencias";
	
	Uri file;
	String fileName = null;
	String filePath = null;
	final int FOTOGRAFIA = 1;
	
	List<String> parametros;
	
	Button guardar;
	Button obtenerDir;
	Spinner tipo_poi;
	CheckBox checkbox_poi;
	EditText nombre_poi;
	EditText descripcion_poi;
	EditText latitud_poi;
	EditText longitud_poi;
	EditText altitud_poi;
	EditText url_poi;
	TextView direccion_poi;
	ImageButton tomarFoto;
	
	LocationManager locationManager;

	private ProgressDialog progress;
	private Activity crearPoi;
	Uploader ups;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.crear_poi);
		
		SharedPreferences prefs = getSharedPreferences("preferencias",Context.MODE_PRIVATE);
		ip_cargada= prefs.getString("ip", "");
		
		URL=ip_cargada.concat(CREARPOI_SERVICES);
		crearPoi = this;
		
		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		guardar = (Button) findViewById(R.id.boton_guardar_poi);
		obtenerDir = (Button) findViewById(R.id.obtener_dir);
		tipo_poi = (Spinner) findViewById(R.id.tipoPoi);
		nombre_poi = (EditText) findViewById(R.id.nombre_poi);
		url_poi = (EditText) findViewById(R.id.url_poi);
		descripcion_poi = (EditText) findViewById(R.id.descripcion_poi);
		checkbox_poi = (CheckBox) findViewById(R.id.checkbox_poi);
		tomarFoto = (ImageButton) findViewById(R.id.imageButton);
		latitud_poi = (EditText) findViewById(R.id.latitud_poi);
		longitud_poi = (EditText) findViewById(R.id.longitud_poi);
		altitud_poi = (EditText) findViewById(R.id.altitud_poi);
		direccion_poi = (TextView) findViewById(R.id.direccion_poi);

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.tipo_pois, android.R.layout.simple_spinner_item);
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		tipo_poi.setAdapter(adapter);

		guardar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// Uploader ups=null;

				parametros = new ArrayList<String>();

				// ----- VALIDAR CAMPOS--------------------------------------
				boolean valido = true;

				if (nombre_poi.getText().toString().length() > 1)
					parametros.add(nombre_poi.getText().toString());
				else
					valido = false;
				parametros.add(descripcion_poi.getText().toString());
				if (checkbox_poi.isChecked())
					parametros.add("1");
				else
					parametros.add("0");
				parametros.add(url_poi.getText().toString());

				if (latitud_poi.getText().toString().length() > 0)
					parametros.add(latitud_poi.getText().toString());
				else
					valido = false;

				if (longitud_poi.getText().toString().length() > 0)
					parametros.add(longitud_poi.getText().toString());
				else
					valido = false;

				if (altitud_poi.getText().toString().length() > 0)
					parametros.add(altitud_poi.getText().toString());
				else
					valido = false;

				// Obtener idUser de shared preferences
				SharedPreferences prefs = getSharedPreferences(nombrePref,
						MODE_PRIVATE);

				parametros.add(prefs.getString("id", ""));
				// ...........................................................

				parametros.add(String.valueOf((tipo_poi
						.getSelectedItemPosition() + 1)));

				if (direccion_poi.getText().toString().length() > 0)
					parametros.add(direccion_poi.getText().toString());
				else
					parametros.add("No especificada");

				if (valido) {
					// ------SUBIR FOTO A
					// SERVIDOR-------------------------------

					new EnviarDatos().execute();
					// System.out.println(filePath);
					// System.out.println(fileName);
					// sinc.getStatus();
					// Uploader ups =new
					// Uploader(SendImageActivity.this,URL,filePath,fileName,parametros);

					// ups.run();

					// ............................................................

				} else {
					Toast.makeText(SendImageActivity.this, "Campos no validos",
							Toast.LENGTH_LONG).show();
				}
			}
		});
		tomarFoto.setOnClickListener(onClickFoto);
		obtenerDir.setOnClickListener(onClickDireccion);

		findViewById(R.id.menu_button).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						int width = (int) TypedValue.applyDimension(
								TypedValue.COMPLEX_UNIT_DIP, 40, getResources()
										.getDisplayMetrics());
						SlideoutActivity.prepare(crearPoi,
								R.id.inner_content, width);
						startActivity(new Intent(crearPoi,
								MenuActivity.class));
						overridePendingTransition(0, 0);
					}
				});

		// -------Sirve para obtener foto-----------------------------
		if (savedInstanceState != null) {
			if (savedInstanceState.getString("Foto") != null) {
				tomarFoto.setImageURI(Uri.parse(savedInstanceState
						.getString("Foto")));
				file = Uri.parse(savedInstanceState.getString("Foto"));
				tomarFoto.setImageBitmap(BitmapFactory.decodeFile(file.getPath()));
				tomarFoto.setImageURI(file);
				filePath = file.getPath();
			}
		}
		// ............................................................

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			int width = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, 40, getResources()
							.getDisplayMetrics());
			SlideoutActivity.prepare(crearPoi,
					R.id.inner_content, width);
			startActivity(new Intent(crearPoi, MenuActivity.class));
			overridePendingTransition(0, 0);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			moveTaskToBack(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onSaveInstanceState(Bundle bundle) {
		if (file != null) {
			bundle.putString("Foto", file.toString());
		}
		super.onSaveInstanceState(bundle);
	}

	View.OnClickListener onClickFoto = new View.OnClickListener() {
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			fileName = Calendar.getInstance().getTimeInMillis() + ".jpg";
			File photo = new File(Environment.getExternalStorageDirectory(),
					String.valueOf(fileName));
			file = Uri.fromFile(photo);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
			startActivityForResult(intent, FOTOGRAFIA);
		}
	};

	View.OnClickListener onClickGuardar = new View.OnClickListener() {
		public void onClick(View v) {

			// Uploader ups=null;

			parametros = new ArrayList<String>();

			// ----- VALIDAR CAMPOS--------------------------------------
			boolean valido = true;

			if (nombre_poi.getText().toString().length() > 1)
				parametros.add(nombre_poi.getText().toString());
			else
				valido = false;
			parametros.add(descripcion_poi.getText().toString());
			if (checkbox_poi.isChecked())
				parametros.add("1");
			else
				parametros.add("0");
			parametros.add(url_poi.getText().toString());

			if (latitud_poi.getText().toString().length() > 0)
				parametros.add(latitud_poi.getText().toString());
			else
				valido = false;

			if (longitud_poi.getText().toString().length() > 0)
				parametros.add(longitud_poi.getText().toString());
			else
				valido = false;

			if (altitud_poi.getText().toString().length() > 0)
				parametros.add(altitud_poi.getText().toString());
			else
				valido = false;

			// Obtener idUser de shared preferences
			SharedPreferences prefs = getSharedPreferences(nombrePref,
					MODE_PRIVATE);

			parametros.add(prefs.getString("id", ""));
			// ...........................................................

			parametros
					.add(String.valueOf((tipo_poi.getSelectedItemPosition() + 1)));

			if (direccion_poi.getText().toString().length() > 0)
				parametros.add(direccion_poi.getText().toString());
			else
				parametros.add("No especificada");

			if (valido) {
				// ------SUBIR FOTO A SERVIDOR-------------------------------

				new EnviarDatos().execute();
				// System.out.println(filePath);
				// System.out.println(fileName);
				// sinc.getStatus();
				// Uploader ups =new
				// Uploader(SendImageActivity.this,URL,filePath,fileName,parametros);

				// ups.run();

				// ............................................................

			} else {
				Toast.makeText(SendImageActivity.this, "Campos no validos",
						Toast.LENGTH_LONG).show();
			}

		}
	};

	View.OnClickListener onClickDireccion = new View.OnClickListener() {
		public void onClick(View v) {
			Geocoder g = new Geocoder(getApplicationContext());
			List<Address> ad = null;
			try {
				ad = g.getFromLocation(
						Double.valueOf(latitud_poi.getText().toString()),
						Double.valueOf(longitud_poi.getText().toString()), 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (ad != null && ad.isEmpty() == false) {
				direccion_poi.setText(ad.get(0).getThoroughfare() + ","
						+ ad.get(0).getSubAdminArea() + ","
						+ ad.get(0).getCountryName());
			}
		}
	};

	@Override
	public void onActivityResult(int RequestCode, int ResultCode, Intent intent) {
		if (RequestCode == FOTOGRAFIA) {
			if (ResultCode == RESULT_OK) {
				//Resources res = getResources();
				
				//tomarFoto.setImageDrawable((res.getDrawable(R.drawable.vista_prev)));
				tomarFoto.setImageURI(file);
				tomarFoto.setAdjustViewBounds(true);
				filePath = file.getPath();
			} else {
				Toast.makeText(getApplicationContext(), "fotografia No tomada",
						Toast.LENGTH_SHORT).show();
				filePath = null;
			}

		}
	}

	LocationListener locationListener = new LocationListener() {

		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			latitud_poi.setText(String.valueOf(location.getLatitude()));
			longitud_poi.setText(String.valueOf(location.getLongitude()));
			altitud_poi.setText(String.valueOf(location.getAltitude()));

		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

	};

	@Override
	public void onPause() {
		super.onPause();
		locationManager.removeUpdates(locationListener);
	}

	@Override
	public void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, locationListener);
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
	}

	public class EnviarDatos extends AsyncTask<Void, Void, Void> {
		List<String> estatus = new ArrayList<String>();

		protected void onPreExecute() {

			progress = ProgressDialog.show(crearPoi, "Enviando...",
					"Por favor espere", true);

		}

		protected void onPostExecute(Void p) {

			progress.dismiss();

			for (String msj : estatus)
				Toast.makeText(SendImageActivity.this, msj, Toast.LENGTH_LONG)
						.show();
		}

		@Override
		protected Void doInBackground(Void... params) {

			try {
				ups = new Uploader(URL, filePath, fileName, parametros);
				ups.uploadForm();
				estatus.add(ups.getStatusForm());
				if (filePath != null) {
					ups.uploadImage();
					estatus.add(ups.getStatus());
				}

			} catch (Exception e) {
				
				e.printStackTrace();
				estatus.add(e.getMessage());
			}
			return null;
		}

	}

}